<?php

class Application_Model_ImmeubleMapper
{
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Immeuble');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Immeuble $imm)
	{
		$data = array(
				'idgestionnaire'=> $imm->getIdGestionnaire(),
				'nomimm' 		=> $imm->getNom(),
				'adresseimm'	=> $imm->getAdresse(),
				'cpimm'			=> $imm->getCp(),
				'villeimm' 		=> $imm->getVille(),
				'noteimm'   	=> $imm->getNote(),
		);
	
		if (null === ($id = $imm->getId())) {
			unset($data['idimmeuble']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('idimmeuble = ?' => $id));
		}
	}
	
	public function find($id, Application_Model_Immeuble $imm)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$imm->setId($row->idimmeuble)
			->setIdGestionnaire($row->idgestionnaire)
			->setNom($row->nomimm)
			->setAdresse($row->adresseimm)
			->setCp($row->cpimm)
			->setVille($row->villeimm)
			->setNote($row->noteimm);
	}
	
	public function fetchAll()
	{
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_Utilisateur();
			$entry->setId($row->idimmeuble)
				->setIdGestionnaire($row->idgestionnaire)
				->setNom($row->nomimm)
				->setAdresse($row->adresseimm)
				->setCp($row->cpimm)
				->setVille($row->villeimm)
				->setNote($row->noteimm);
			$entries[] = $entry;
		}
		return $entries;
	}

}

